package com.cunshe.service;

import com.cunshe.dao.ProductDao;
import com.cunshe.domain.Product;
import com.cunshe.domain.ProductImage;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 产品
 * @author xiao
 */
@Mapper
@Repository
public class ProductService {

    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductImageService productImageService;

    /** 新增 */
    @Transactional(rollbackFor = Exception.class)
    public int insert(Product record, List<String> images) {
        record.setCreatetime(new Date());
        productDao.insert(record);

        int i = 0;
        for (String image : images) {
            ProductImage build = ProductImage.builder()
                    .productId(record.getId())
                    .url(image)
                    .sortNum(i++)
                    .build();
            productImageService.insert(build);
        }

        return 1;
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        return productDao.delete(id);
    }

    /** 修改 */
    @Transactional(rollbackFor = Exception.class)
    public int update(Product record, List<String> images) {
        record.setUpdatetime(new Date());
        productDao.update(record);

        productImageService.deleteByProductId(record.getId());
        int i = 0;
        if(!CollectionUtils.isEmpty(images)) {
            for (String image : images) {
                ProductImage build = ProductImage.builder()
                        .productId(record.getId())
                        .url(image)
                        .sortNum(i++)
                        .build();
                productImageService.insert(build);
            }
        }

        return 1;
    }

    /** 查询列表 */
    public Product get(Long id) {
        return list(Product.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    /** 查询列表 */
    public List<Product> list(Product record) {
        return productDao.list(record);
    }

}